package automate.learn;

import java.util.ArrayList;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;

public class UserUtilities {
	public ArrayList<User> getUserMSSQLDb() {

		User user1 = new User("iberezen@softserveinc.com", "Marigold2014");
		User user2 = new User("bla-bla@gmail.com", "bla-bla");
		User user3 = new User("email4", "password2");

		ArrayList<User> userList = new ArrayList<User>();
		userList.add(user1);
		userList.add(user2);
		userList.add(user3);

		return userList;
	}

	public ArrayList<User> getUserFromMySQLDb() {

		User user1 = new User("iberezen@softserveinc.com", "Marigold2014");
		User user2 = new User("bla-bla@gmail.com", "bla-bla");
		User user3 = new User("email4", "password2");

		ArrayList<User> userList = new ArrayList<User>();
		userList.add(user1);
		userList.add(user2);
		userList.add(user3);

		return userList;
	}

	public ArrayList<User> getUsersFromXMLFile(String fileName) throws Exception {
		
		File file = new File(fileName);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(file);
		doc.getDocumentElement().normalize();
		System.out.println("Root element "
		        + doc.getDocumentElement().getNodeName());
		NodeList nodeLst = doc.getElementsByTagName("userLogin");
		ArrayList<User> users = new ArrayList<User>();

		for (int s = 0; s < nodeLst.getLength(); s++) {

			User user = new User();
			Node fstNode = nodeLst.item(s);

			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

				Element fstElmnt = (Element) fstNode;
				NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("email");
				Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
				NodeList fstNm = fstNmElmnt.getChildNodes();
				Node emailNode = (Node) fstNm.item(0);
				String email = emailNode.getNodeValue();
				user.setUserName(email);
				System.out.println("E-mail : " + email);

				NodeList lstNmElmntLst = fstElmnt
				        .getElementsByTagName("password");
				Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
				NodeList lstNm = lstNmElmnt.getChildNodes();
				String password = ((Node) lstNm.item(0)).getNodeValue();
				user.setPassword(password);
				System.out.println("Password : "
				        + ((Node) lstNm.item(0)).getNodeValue());

				users.add(user);
			}
		}

		return users;

	}
}
